<template>
  <div class="main">
    <!-- 使用 t('mine.title') 获取翻译文本 -->
    <div class="title">{{ t('mine.title') }}</div>

    <el-card class="card">
      <template #header>
        <div class="card-header">
          <!-- 使用 t('mine.baseMsg') 获取翻译文本 -->
          <span>{{ t('mine.baseMsg') }}</span>
        </div>
      </template>
      <div class="contain">
        <div class="basic">
          <div class="avatar" @click="triggerFileInput">
            <el-avatar :size="70" :src="userInfo.avatar" class="avatar-img" />
            <!-- 添加头像选择器，隐藏文件选择器 -->
            <input type="file" accept="image/*" class="avatar-input" ref="fileInput" @change="handleAvatarChange" />
          </div>
          <div class="name">
            <div class="name_text">{{ userInfo.username }}</div>

            <!-- 使用 el-popover 创建气泡输入框 -->
            <el-popover trigger="click" v-model:visible="popoverVisible" width="250" placement="bottom"
              @before-leave="cancelEdit">
              <el-input v-model="newName" placeholder="输入新的名字" size="small" class="name-input" @blur="saveName" />
              <div class="button-group">
                <!-- 确认和取消按钮，居中对齐 -->
                <el-button style=" margin-top: 10px; margin-left: 50px;" size="small" type="primary"
                  @click="saveName">确认</el-button>
                <el-button style="margin-top: 10px; margin-left: 30px;" size="small" @click="cancelEdit">取消</el-button>
              </div>
              <template #reference>
                <el-icon class="name_icon">
                  <Edit />
                </el-icon>
              </template>
            </el-popover>
          </div>
        </div>
        <div class="phone">
          <!-- 使用 t('mine.phone') 获取翻译文本 -->
          <span class="phone_text">{{ t('mine.phone') }}</span>
          {{ userInfo.phone }}
        </div>
      </div>
    </el-card>
<!-- 系统日志部分 -->
    <el-card class="card">
      <template #header>
        <div class="card-header">
          <!-- 使用 t('mine.sysLog') 获取翻译文本 -->
          <span>{{ t('mine.sysLog') }}</span>
        </div>
      </template>
      <div class="contain">
        <el-card v-for="(card, index) in cardData " :key="index">
          <div class="card-info">
            <div class="left">
              <svg-icon name="computer" width="3rem" height="3rem"></svg-icon>
            </div>
            <div class="right">
              <ul class="info-list">
                <li class="info-detail">
                  <svg-icon name="systemType" width="1rem" height="1rem"></svg-icon>
                  <span style="margin-left: 2px;">{{ card.systemType }}</span>
                </li>
                <li class="info-detail">
                  <svg-icon name="browser" width="1rem" height="1rem"></svg-icon>
                  <span style="margin-left: 4px;">{{ card.browserType }}</span>
                </li>
              </ul>
              <span class="login_time">{{ formatDate(card.loginTime) }}</span>
            </div>
          </div>
        </el-card>
      </div>
      <!-- 分页组件 -->
      <!-- <el-pagination :current-page="currentPage" :page-size="pageSize" :total="totalPage"
        @current-change="handlePageChange" layout="prev, pager, next, jumper" class="el-pagination" /> -->
          <!-- ...其他内容 -->
    <Pagination
      v-model:current="currentPage"
      v-model:pageSize="pageSize"
      :total="totalRecords"
      @pagination-change="fetchLogs"
      class="el-pagination"
    />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import {t} from '../../../locales/index'
import { ref,  onMounted } from 'vue';
import { Edit } from '@element-plus/icons-vue';
import { reqUserInfo, reqChageUserName, reqLoginLogs } from '../../../api/user/index';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';

// 转换时间格式
const formatDate = (dateString: string): string => {
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss'); // 格式化为更友好的日期时间格式
};


// 定义用户信息对象
interface UserInfo {
  avatar: string;
  id: number;
  username: string;
  phone: string;
}

// 定义日志数据类型
interface LogData{
  browserType: string;
  loginTime: string;
  systemType: string;
}

const userInfo = ref<UserInfo>({
  avatar: '',
  id: 0,
  username: '',
  phone: ''
});

const cardData = ref<LogData[]>([]);
const popoverVisible = ref(false); // 控制 popover 显示与隐藏
const newName = ref(''); // 新名字的输入框
const currentPage = ref(1); // 当前页数
const pageSize = ref(10); // 每页显示条数
// const totalPage = ref(0); // 总页数
const totalRecords = ref(0) // 注意这里改为总记录数
const fileInput = ref<HTMLInputElement | null>(null); // 文件选择器的引用

// 在 onMounted 钩子中调用封装的方法
onMounted(() => {
  fetchUserInfo();
  fetchLogs();
});

// 获取用户信息
const fetchUserInfo = async () => {
  const res = await reqUserInfo();
  if (res.data && res.code === 200) {
    userInfo.value = res.data; // 更新用户信息
    localStorage.setItem('username',userInfo.value.username)
  } else {
    ElMessage.error(res.msg || "用户信息获取错误");
  }
};

// 获取日志数据方法
const fetchLogs = async () => {
  const res = await reqLoginLogs(pageSize.value, currentPage.value)
  if (res.code === 200) {
    cardData.value = res.data.datas.map((log: any) => ({
      browserType: log.browserType,
      loginTime: log.loginTime,
      systemType: log.systemType
    }))
    totalRecords.value = res.data.total // 这里改为总记录数
  }
}




// 处理头像改变
const handleAvatarChange = (event: Event) => {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files[0]) {
    const file = input.files[0];
    userInfo.value.avatar = URL.createObjectURL(file); // 更新头像
  }
};

// 触发文件选择器的点击事件
const triggerFileInput = () => {
  if (fileInput.value) {
    fileInput.value.click(); // 模拟点击文件选择器
  }
};

// 保存新名字的方法
const saveName = async () => {
  if (newName.value.trim()) {
    const res = await reqChageUserName(newName.value);
    if (res.code === 200) {
  
      localStorage.setItem('username',newName.value)
      ElMessage.success('修改成功');
      fetchUserInfo();
    } else {
      ElMessage.error(res.msg || "修改失败");
    }
  }
  popoverVisible.value = false; // 关闭气泡
};

// 取消编辑的方法
const cancelEdit = () => {
  newName.value = ''; // 清空输入框
  popoverVisible.value = false;
};
</script>


<style scoped lang="scss">
.main {
  padding: 0 1vw;


  .title {
    margin-bottom: 30px;
    font-size: 2rem;
  }

  .card {
    padding: 10px;
    border-radius: 20px;
    margin-bottom: 30px;

  }

  .card-header {
    font-weight: 700;
  }

  .basic {
    display: flex;
    align-items: center;
    margin-bottom: 1.5vw;

    .avatar {
      margin-right: 1.3vw;
      position: relative;
      cursor: pointer;
      /* 让头像区域也能点击 */

      .avatar-img {
        transition: filter 0.3s ease;
      }

      .avatar-img:hover {
        filter: brightness(0.7);
        /* 暗化效果 */
      }

      /* 文件选择器样式 */
      .avatar-input {
        position: absolute;
        bottom: 0;
        right: 0;
        opacity: 0;
        /* 隐藏选择器 */
        width: 30px;
        height: 30px;
        cursor: pointer;
      }
    }

    .name {
      display: flex;
      align-items: center;

      .name_text {
        font-size: 1.5rem;
        margin-right: 3px;
      }

      .name_icon {
        margin-top: 7px;
        font-size: 1.1rem;
        color: rgb(104, 164, 249);
        cursor: pointer;

        :hover {
          color: rgba(104, 164, 249, 0.566);
        }
      }
    }
  }

  .phone {
    .phone_text {
      color: rgb(136, 136, 136);
      margin-right: 1vw;
    }
  }

  /* 美化气泡输入框 */
  .el-popover {
    border-radius: 8px;
    padding: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
    background-color: #fff;
  }

  .name-input {
    width: 100%;
    /* 输入框宽度调整 */
    border-radius: 4px;
    margin-bottom: 10px;
  }



  .el-button {

    width: 100px;
    /* 固定按钮宽度 */
    border-radius: 4px;
  }

  .el-button[type='primary'] {
    background-color: #409eff;
    border-color: #409eff;
  }

  .el-button[type='primary']:hover {
    background-color: #66b1ff;
    border-color: #66b1ff;
  }

  .el-button:hover {
    background-color: #f0f0f0;
  }
}











// card样式
.el-card {
  margin-bottom: 1rem;
  padding: 0.5rem;
  cursor: pointer;

  .card-info {
    display: flex;
    align-items: center;
    transition: transform 0.3s ease; // 添加过渡效果

    &:hover {
      // 添加悬停效果
      transform: scale(1.02); // 放大一点
    }



    .right {
      margin-left: 2vw;

      .info-list {
        display: flex;
        list-style: none;
        padding: 0;
        margin-top: 0.6rem;

        li {
          display: flex;
          align-items: center;
          color: #6a6969d9;
        }

        li::after {
          content: '·';
          margin: 0 0.6rem;
        }

        li:last-child::after {
          content: '';
        }

        .info-detail {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
         

        }

        .login_time {
          display: flex;
        }
      }
    }

  }






}



// .el-pagination {
//   margin-top: 20px;
//   display: flex;
//   justify-content: center;
// }
</style>